<template>
  <div class="editor-page">
    <main class="editor-main">
      <!-- 编辑区 -->
      <section class="editor-box">
        <!-- 标题输入 -->
        <el-input
          v-model="pageTitle"
          placeholder="请输入标题"
          class="title-input"
          size="large"
          clearable
        />

        <!-- 工具栏 -->
        <div class="editor-toolbar">
          <!-- 加粗 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('bold') }"
            @click="toggleBold"
            title="加粗"
          >
            <svg viewBox="0 0 24 24">
              <text x="4" y="18" font-weight="bold" font-size="16" fill="#000">B</text>
            </svg>
          </button>

          <!-- 斜体 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('italic') }"
            @click="toggleItalic"
            title="斜体"
          >
            <svg viewBox="0 0 24 24">
              <text x="4" y="18" font-style="italic" font-size="16" fill="#000">I</text>
            </svg>
          </button>

          <!-- 下划线 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('underline') }"
            @click="toggleUnderline"
            title="下划线"
          >
            <svg viewBox="0 0 24 24">
              <text x="4" y="18" font-size="16" fill="#000" text-decoration="underline">U</text>
            </svg>
          </button>

          <!-- 删除线 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('strike') }"
            @click="toggleStrike"
            title="删除线"
          >
            <svg viewBox="0 0 24 24">
              <text x="4" y="18" font-size="16" fill="#000" text-decoration="line-through">S</text>
            </svg>
          </button>

          <!-- 无序列表 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('bulletList') }"
            @click="toggleBulletList"
            title="无序列表"
          >
            <svg viewBox="0 0 24 24">
              <circle cx="4" cy="6" r="2" fill="#000" />
              <rect x="8" y="5" width="12" height="2" fill="#000" />
              <circle cx="4" cy="12" r="2" fill="#000" />
              <rect x="8" y="11" width="12" height="2" fill="#000" />
              <circle cx="4" cy="18" r="2" fill="#000" />
              <rect x="8" y="17" width="12" height="2" fill="#000" />
            </svg>
          </button>

          <!-- 有序列表 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive('orderedList') }"
            @click="toggleOrderedList"
            title="有序列表"
          >
            <svg viewBox="0 0 24 24">
              <text x="2" y="7" font-size="8" fill="#000">1</text>
              <rect x="8" y="5" width="12" height="2" fill="#000" />
              <text x="2" y="13" font-size="8" fill="#000">2</text>
              <rect x="8" y="11" width="12" height="2" fill="#000" />
              <text x="2" y="19" font-size="8" fill="#000">3</text>
              <rect x="8" y="17" width="12" height="2" fill="#000" />
            </svg>
          </button>

          <!-- 对齐按钮 -->
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive({ textAlign: 'left' }) }"
            @click="setTextAlign('left')"
            title="左对齐"
          >
            <svg viewBox="0 0 24 24">
              <rect x="4" y="6" width="16" height="2" fill="#000" />
              <rect x="4" y="10" width="12" height="2" fill="#000" />
              <rect x="4" y="14" width="16" height="2" fill="#000" />
              <rect x="4" y="18" width="12" height="2" fill="#000" />
            </svg>
          </button>
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive({ textAlign: 'center' }) }"
            @click="setTextAlign('center')"
            title="居中对齐"
          >
            <svg viewBox="0 0 24 24">
              <rect x="6" y="6" width="12" height="2" fill="#000" />
              <rect x="4" y="10" width="16" height="2" fill="#000" />
              <rect x="6" y="14" width="12" height="2" fill="#000" />
              <rect x="4" y="18" width="16" height="2" fill="#000" />
            </svg>
          </button>
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive({ textAlign: 'right' }) }"
            @click="setTextAlign('right')"
            title="右对齐"
          >
            <svg viewBox="0 0 24 24">
              <rect x="8" y="6" width="12" height="2" fill="#000" />
              <rect x="4" y="10" width="16" height="2" fill="#000" />
              <rect x="8" y="14" width="12" height="2" fill="#000" />
              <rect x="4" y="18" width="16" height="2" fill="#000" />
            </svg>
          </button>
          <button
            class="toolbar-btn"
            :class="{ active: editor.isActive({ textAlign: 'justify' }) }"
            @click="setTextAlign('justify')"
            title="两端对齐"
          >
            <svg viewBox="0 0 24 24">
              <rect x="4" y="6" width="16" height="2" fill="#000" />
              <rect x="4" y="10" width="16" height="2" fill="#000" />
              <rect x="4" y="14" width="16" height="2" fill="#000" />
              <rect x="4" y="18" width="16" height="2" fill="#000" />
            </svg>
          </button>

          <!-- 插入图片/视频 -->
          <button class="toolbar-btn" @click="insertImage" title="插入图片">
            <svg viewBox="0 0 24 24">
              <rect
                x="2"
                y="4"
                width="20"
                height="16"
                rx="2"
                fill="none"
                stroke="#000"
                stroke-width="2"
              />
              <circle cx="8" cy="9" r="2" fill="#000" />
              <path d="M2 20l6-6 5 5 9-9" stroke="#000" stroke-width="2" fill="none" />
            </svg>
          </button>
          <button class="toolbar-btn" @click="insertVideo" title="插入视频">
            <svg viewBox="0 0 24 24">
              <rect
                x="2"
                y="4"
                width="20"
                height="16"
                rx="2"
                fill="none"
                stroke="#000"
                stroke-width="2"
              />
              <polygon points="10,8 16,12 10,16" fill="#000" />
            </svg>
          </button>

          <!-- 撤销/重做 -->
          <button class="toolbar-btn" @click="undo" title="撤销">
            <svg viewBox="0 0 24 24">
              <path d="M12 4v4h4" stroke="#000" stroke-width="2" fill="none" />
              <path d="M8 12a4 4 0 1 1 4 4" stroke="#000" stroke-width="2" fill="none" />
            </svg>
          </button>
          <button class="toolbar-btn" @click="redo" title="重做">
            <svg viewBox="0 0 24 24">
              <path d="M12 4v4h-4" stroke="#000" stroke-width="2" fill="none" />
              <path d="M16 12a4 4 0 1 0-4 4" stroke="#000" stroke-width="2" fill="none" />
            </svg>
          </button>

          <!-- 文字颜色 -->
          <button class="toolbar-btn" @click="showColorPicker = !showColorPicker" title="文字颜色">
            <svg viewBox="0 0 24 24">
              <rect x="4" y="6" width="16" height="12" fill="none" stroke="#000" stroke-width="2" />
              <line x1="4" y1="18" x2="20" y2="18" stroke="#000" stroke-width="2" />
            </svg>
          </button>
          <div v-if="showColorPicker" class="color-picker">
            <input type="color" v-model="fontColor" @change="setFontColor" />
          </div>

          <!-- 清空 -->
          <button class="toolbar-btn" @click="clearContent" title="清空内容">
            <svg viewBox="0 0 24 24">
              <rect x="5" y="5" width="14" height="14" fill="none" stroke="#000" stroke-width="2" />
              <line x1="5" y1="5" x2="19" y2="19" stroke="#000" stroke-width="2" />
              <line x1="19" y1="5" x2="5" y2="19" stroke="#000" stroke-width="2" />
            </svg>
          </button>
        </div>

        <!-- 编辑器内容 -->
        <EditorContent :editor="editor" class="tiptap-editor" />
      </section>

      <!-- 预览区 -->
      <section class="preview-box">
        <h2 class="preview-title">{{ pageTitle || '预览标题' }}</h2>
        <div class="preview-content" v-html="editor.getHTML() || ''"></div>
      </section>
    </main>

    <!-- 导出 -->
    <div class="floating-actions">
      <el-button type="primary" @click="exportHtml">导出网页</el-button>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onBeforeUnmount } from 'vue'
import { Editor, EditorContent } from '@tiptap/vue-3'
import StarterKit from '@tiptap/starter-kit'
import Underline from '@tiptap/extension-underline'
import Strike from '@tiptap/extension-strike'
import { TextStyle } from '@tiptap/extension-text-style'
import Color from '@tiptap/extension-color'
import TextAlign from '@tiptap/extension-text-align'
import Image from '@tiptap/extension-image'
import Placeholder from '@tiptap/extension-placeholder'
import ResizeImage from 'tiptap-extension-resize-image'

import { uploadFile } from '@/api/upload' // 引入接口文件

const pageTitle = ref('')
const fontColor = ref('#000000')
const showColorPicker = ref(false)

const editor = new Editor({
  extensions: [
    StarterKit,
    Underline,
    Strike,
    TextStyle,
    Color,
    TextAlign.configure({ types: ['paragraph', 'heading'] }),
    Image.configure({ inline: false }),
    ResizeImage,
    Placeholder.configure({
      placeholder: '开始编辑...',
      showOnlyWhenEditable: true,
      emptyEditorClass: 'is-editor-empty'
    })
  ],
  content: ''
})

const toggleBold = () => editor.chain().focus().toggleBold().run()
const toggleItalic = () => editor.chain().focus().toggleItalic().run()
const toggleUnderline = () => editor.chain().focus().toggleUnderline().run()
const toggleStrike = () => editor.chain().focus().toggleStrike().run()
const toggleBulletList = () => editor.chain().focus().toggleBulletList().run()
const toggleOrderedList = () => editor.chain().focus().toggleOrderedList().run()
const setTextAlign = (align: 'left' | 'center' | 'right' | 'justify') =>
  editor.chain().focus().setTextAlign(align).run()
const undo = () => editor.chain().focus().undo().run()
const redo = () => editor.chain().focus().redo().run()
const clearContent = () => {
  pageTitle.value = ''
  editor.commands.clearContent()
}
const setFontColor = () =>
  editor.chain().focus().setMark('textStyle', { color: fontColor.value }).run()

// -------------------- 图片/视频上传 --------------------
const insertImage = async () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.click()
  input.onchange = async () => {
    const file = input.files?.[0]
    if (!file) return

    try {
      const res = await uploadFile(file) // 调用接口
      if (res.code === 200 && res.url) {
        editor.chain().focus().setImage({ src: res.url, width: 200 }).run()
      }
    } catch (err) {
      console.error('图片上传失败:', err)
      alert('图片上传失败，请重试')
    }
  }
}

const insertVideo = async () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'video/*'
  input.click()
  input.onchange = async () => {
    const file = input.files?.[0]
    if (!file) return

    try {
      const res = await uploadFile(file) // 调用接口
      if (res.code === 200 && res.url) {
        editor
          .chain()
          .focus()
          .insertContent(
            `<video controls src="${res.url}" style="max-width:100%;height:auto;"></video>`
          )
          .run()
      }
    } catch (err) {
      console.error('视频上传失败:', err)
      alert('视频上传失败，请重试')
    }
  }
}

// -------------------- 导出 HTML --------------------
const exportHtml = () => {
  const html = `
  <!DOCTYPE html>
  <html lang="zh">
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
    <title>${pageTitle.value || '网页'}</title>
    <style>
      body{font-family:Arial;padding:20px;line-height:1.6;}
      img,video{max-width:100%;height:auto;}
    </style>
  </head>
  <body>
    <h1>${pageTitle.value || '标题'}</h1>
    ${editor.getHTML()}
  </body>
  </html>`
  const blob = new Blob([html], { type: 'text/html' })
  const link = document.createElement('a')
  link.href = URL.createObjectURL(blob)
  link.download = `${pageTitle.value || '网页'}.html`
  link.click()
}

onBeforeUnmount(() => editor.destroy())
</script>

<style scoped>
.editor-page {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background: #f5f7fa;
}
.editor-main {
  flex: 1;
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 12px;
  padding: 12px;
}
.editor-box {
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  overflow: hidden;
}
.title-input {
  margin: 12px 12px 6px 12px;
}
.editor-toolbar {
  display: flex;
  flex-wrap: wrap;
  gap: 6px;
  padding: 6px 12px;
  background: #fafafa;
  position: sticky;
  top: 0;
  z-index: 10;
  box-shadow: 0 2px 6px rgba(0, 0, 0, 0.05);
}
.toolbar-btn {
  width: 32px;
  height: 32px;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  background: none;
  cursor: pointer;
  border-radius: 4px;
}
.toolbar-btn:hover {
  background: #e6f0ff;
}
.toolbar-btn.active {
  background: #d0e6ff;
}
.color-picker {
  position: absolute;
  margin-top: 4px;
}
.tiptap-editor {
  flex: 1;
  padding: 16px;
  border: none;
  min-height: 500px;
  background: #fff;
  font-size: 15px;
  line-height: 1.6;
}
.tiptap-editor:focus {
  outline: none;
}
.tiptap-editor.is-editor-empty::before {
  content: attr(data-placeholder);
  color: #aaa;
  float: left;
  pointer-events: none;
  height: 0;
}
.preview-box {
  display: flex;
  flex-direction: column;
  background: #fff;
  border-radius: 8px;
  padding: 12px;
  overflow: auto;
}
.preview-title {
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 12px;
  color: #333;
}
.preview-content {
  flex: 1;
  overflow: auto;
  white-space: pre-wrap;
}
.floating-actions {
  position: fixed;
  right: 20px;
  bottom: 20px;
}
</style>
